import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.dz.glory.common.vo.Ret;
import com.dz.glory.core.base.controller.BaseController;
import com.dz.glory.core.base.tips.ErrorTip;
import com.dz.glory.core.common.annotion.BussinessLog;
import com.dz.glory.core.common.annotion.Permission;
import com.dz.glory.core.common.constant.factory.PageFactory;
import com.dz.glory.core.log.LogObjectHolder;
import org.apache.commons.collections4.CollectionUtils;
import com.dz.glory.tools.StringUtils;
import org.apache.dubbo.config.annotation.DubboReference;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.lang.invoke.MethodHandles;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * ${table.comment} 控制器
 * </p>
 *
 * @author ${author}
 * @since ${date?date}
 */
@Controller
@RequestMapping("${package.Parent}")
public class ${entity}Controller extends BaseController {

    private static final Logger logger = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass());

    private final String PREFIX = "/beast/${package.Parent}/";

    @DubboReference
    private ${entity}ServiceRpc ${entity?uncap_first}Service;

    /**
     * 跳转到${moduleName}首页
     */
    @RequestMapping("")
    public String index() {
        return PREFIX + "${entity?uncap_first}.html";
    }

    /**
     * 跳转到添加${moduleName}
     */
    @RequestMapping("/${package.Parent}_add")
    public String ${package.Parent}Add(Model model) {
        return PREFIX + "${entity?uncap_first}_add.html";
    }

    /**
     * 跳转到修改${moduleName}
     */
    @RequestMapping("/${package.Parent}_update/{id}")
    public String ${package.Parent}Update(@PathVariable("id") Integer id, Model model) {
        Ret<${entity}VO> ret = ${entity?uncap_first}Service.getById(id);
        if (ret != null && ret.success()) {
            ${entity}VO vo = ret.getData();
            model.addAttribute("item", vo);
            LogObjectHolder.me().set(vo);
        }
        return PREFIX + "${entity?uncap_first}_edit.html";
    }

    /**
     * 获取${moduleName}列表
     */
    @RequestMapping(value = "/list")
    @ResponseBody
    public Object list(${entity}Req request) {
        Page<${entity}VO> page = new PageFactory<${entity}VO>().defaultNewPage();
        request.setPageNo(page.getCurrent());
        request.setPageSize(page.getSize());
        com.dz.glory.common.vo.Page<${entity}VO> ret = ${entity?uncap_first}Service.getList(request).getData();
        if (Objects.nonNull(ret.getData())) {
            List<${entity}VO> data = ret.getData();
            PageCovertUtils.covert(page, ret);
        }
        return super.packForBT(page);
    }

    /**
     * 新增${moduleName}
     */
    @Permission
    @RequestMapping(value = "/add")
    @ResponseBody
    @BussinessLog(value = "beast-新增${moduleName}", key = "${table.fields?filter(f -> f.propertyName != "ctime" && f.propertyName != "utime" && f.propertyName != "creator")?map(f -> f.propertyName)?join(",")}", dict = ${entity}Dict.class)
    public Object add(${entity}VO vo) {
        try {
            ShiroUser user = ShiroKit.getUser();
            if (user != null) {
                vo.setCreator(user.getName());
            }
            ${entity?uncap_first}Service.saveOrUpdate(vo);
        } catch (Exception e) {
            logger.error("beast${moduleName}新增异常:{}", e.getMessage(), e);
            return new ErrorTip(500, "新增beast${moduleName}失败！");
        }
        return SUCCESS_TIP;
    }


    /**
     * 修改${moduleName}
     */
    @Permission
    @RequestMapping(value = "/update")
    @ResponseBody
    @BussinessLog(value = "beast-修改${moduleName}", key = "${table.fields?filter(f -> f.propertyName != "ctime" && f.propertyName != "utime" && f.propertyName != "creator")?map(f -> f.propertyName)?join(",")}", dict = ${entity}Dict.class)
    public Object update(${entity}VO vo) {
        try {
            ${entity?uncap_first}Service.saveOrUpdate(vo);
        } catch (Exception e) {
            logger.error("beast${moduleName}更新异常:{}", e.getMessage(), e);
            return new ErrorTip(500, "更新beast${moduleName}失败！");
        }
        return SUCCESS_TIP;
    }

    /**
     * 删除${moduleName}
     */
    @Permission
    @RequestMapping(value = "/delete")
    @ResponseBody
    @BussinessLog(value = "beast-删除${moduleName}", key = "id", dict = ${entity}Dict.class)
    public Object delete(String data) {
        try {
            if (StringUtils.isBlank(data)) {
                return SUCCESS_TIP;
            }
            List<Integer> ids = StringUtils.splitToInteger(data, ",");
            if (CollectionUtils.isNotEmpty(ids)) {
                ${entity?uncap_first}Service.delete(ids);
            }
        } catch (Exception e) {
            logger.error("beast${moduleName}删除异常:{}", e.getMessage(), e);
            return new ErrorTip(500, "删除beast${moduleName}失败！");
        }
        return SUCCESS_TIP;
    }

    /**
     * ${moduleName}详情
     */
    @Permission
    @RequestMapping(value = "/detail/{id}")
    @ResponseBody
    public Object detail(@PathVariable("id") Integer id) {
        return ${entity?uncap_first}Service.getById(id);
    }

<#list table.fields as field>
    <#if field.propertyName == "sort">
    /**
     * 修改排序
     */
    @Permission
    @RequestMapping(value = "/sort")
    @ResponseBody
    @BussinessLog(value = "beast-更新${moduleName}排序", key = "id,sort", dict = ${entity}Dict.class)
    public Object updateSort(Integer id, Integer sort) {
        try {
            ${entity}Req request = new ${entity}Req();
            request.setId(id);
            request.setSort(sort);
            ${entity?uncap_first}Service.updateSort(request);
        } catch (Exception e) {
            logger.error("beast${moduleName}修改排序异常:{}", e.getMessage(), e);
            return new ErrorTip(500, "修改beast${moduleName}排序失败！");
        }
        return SUCCESS_TIP;
    }
    </#if>
    <#if field.propertyName == "status">
    /**
     * 修改状态
     */
    @Permission
    @RequestMapping(value = "/status")
    @ResponseBody
    @BussinessLog(value = "beast-更新${moduleName}状态", key = "id,status", dict = ${entity}Dict.class)
    public Object updateStatus(Integer id, Integer status) {
        try {
            ${entity}Req request = new ${entity}Req();
            request.setId(id);
            request.setStatus(status);
            ${entity?uncap_first}Service.updateStatus(request);
        } catch (Exception e) {
            logger.error("beast${moduleName}修改状态异常:{}", e.getMessage(), e);
            return new ErrorTip(500, "修改beast${moduleName}状态失败！");
        }
        return SUCCESS_TIP;
    }
    </#if>
</#list>
}
